package com.java8.optional;

import com.java8.lambda.bean.Employee;
import org.junit.jupiter.api.Test;

import java.util.Optional;

/**
 * @author xuehu
 * @date 2020/12/1 16:43
 */

public class TestOptional {


    /**
     * Optional.of(T t): 创建一个Optional实例
     * Optional.empty(): 创建一个空的Optional实例。
     * Optional.ofNullable(T t): 若t不为null,创建Optional实例，否则创建空实例
     * isPresent(): 判断是否包含值
     * orElse(T t): 如果调用对象包含值,返回该值,否则返回、
     * orElseGet(Supplier s): 如果调用对象包含值,返回该值,否则返回s获取的值
     * map(Function f) : 如果有值对其处理,并返回处理后的Optional,否则返回Optional.empty()
     * flatMap(Function mapper):与map类似,要求返回值必须是Optional
     */

    @Test
    public void test1() {

//        Optional<Employee> op = Optional.of(new Employee());

        Optional<Employee> op = Optional.of(null); //NullPointerException





        Employee employee = op.get();
        System.out.println(employee);

    }


    @Test
    public void test2() {

        Optional<Employee> optionalEmployee = Optional.ofNullable(null); // java.util.NoSuchElementException: No value present

        Employee employee = optionalEmployee.get();
        System.out.println(employee);


        Optional<Object> empty = Optional.empty();

        System.out.println(empty);


    }


    @Test
    public void test3() {
        Optional<Employee> optionalEmployee = Optional.ofNullable(null);

        optionalEmployee.ifPresent(System.out::println);

        Employee orElse = optionalEmployee.orElse(new Employee("张三", 18, 888.88, Employee.Status.FREE));

        System.out.println(orElse);

        Employee employee = optionalEmployee.orElseGet(Employee::new);

        System.out.println(employee);

    }



}
